<template>
  <div class="combination-add-chunk5">
    <div class="head">
      <div class="h-title">回测参数</div>
      <div class="h-body">
        <el-form ref="dataForm" :rules="rules" :inline="true" label-width="80px" :model="dataForm" class="el-form-center">
          <el-form-item label="组合名称" prop="portfolioName"> 
            <el-input v-model="dataForm.portfolioName" clearable placeholder="请输入组合名称" size="mini" style="width: 260px;"></el-input>
          </el-form-item>
          <el-form-item label="初始资金" prop="portfolioInitMoney"> 
            <el-input-number v-model="dataForm.portfolioInitMoney" clearable placeholder="请输入初始资金" size="mini" style="width: 160px;" @input="moneyChangeHandle" :controls="false"></el-input-number> 万元
          </el-form-item>
          <el-form-item label="初始份额" prop=""> 
            <el-input-number v-model="dataForm.portfolioInitMoney" disabled placeholder="初始份额" size="mini" style="width: 160px;" :controls="false"></el-input-number> 万份
          </el-form-item>
          <el-form-item label="成立日期" label-width="80px" prop="makeTime">
            <el-date-picker
              v-model="dataForm.makeTime"
              type="date"
              size="mini"
              @change="makeTimeChange"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions1"
              placeholder="选择日期"
              style="width: 160px;">
            </el-date-picker>
          </el-form-item> 
        </el-form>
        <el-form :inline="true" label-width="80px" :model="dataForm" class="el-form-center" style="margin-top: 20px;">
          <el-form-item label="备注" prop=""> 
            <el-input type="textarea" :rows="3" placeholder="最多120个字符" v-model="dataForm.mark" maxlength="120" size="mini" show-word-limit style="width: 600px;"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table
        v-if="list.length"
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        stripe fit
        size="mini"
        :cell-style="{padding: '6px 0'}"
        :header-cell-style="{background:'#dcedff',color:'#32639d'}"
        style="width: 100%;margin-top: 20px;"
      >
        <el-table-column type="index" label="序号" align="center" fixed width="60"></el-table-column>
        <el-table-column prop="strategyInfoVo.strategyName" label="策略名称" fixed min-width="200" show-overflow-tooltip> 
          <template slot-scope="{row}">
            {{row.strategyInfoVo.strategyName}}
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="进入组合日期" align="center" fixed width="140">
          <template slot-scope="{$index}">
            <el-date-picker
              v-model="dataForm.strategyPortfolioDetials[$index].enterTime"
              type="date"
              size="mini"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions2"
              placeholder="选择日期"
              style="width: 130px;">
            </el-date-picker>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="份额(份)" align="center" fixed width="120">
          <template slot-scope="{$index}">
            <el-input-number v-model="dataForm.strategyPortfolioDetials[$index].share" style="width: 90px" @input="shareHandleChange($index)" disabled :precision="2" size="mini" :controls="false"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="市值(万元)" align="center" fixed width="120">
          <template slot-scope="{$index}">
            <el-input-number v-model="dataForm.strategyPortfolioDetials[$index].marketValue" style="width: 90px" @input="marketValueHandleChange" disabled :precision="2" size="mini" :controls="false"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="weight" label="权重(%)" align="center" fixed width="100">
          <template slot-scope="{$index}">
            <el-input-number v-model="dataForm.strategyPortfolioDetials[$index].weight" style="width: 70px" @input="weightHandleChange($index)" :min="0" :max="100" :precision="2" size="mini" :controls="false"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="" label="近1月收益率" align="center" width="130">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['1']&&netWorthExtendBeanList[$index]['1'].incomeRate" :class="netWorthExtendBeanList[$index]['1'].incomeRate>=0?'positiveFc':'negativeFc'">
              {{ netWorthExtendBeanList[$index]['1'].incomeRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="近3月收益率" align="center" width="130">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['3']&&netWorthExtendBeanList[$index]['3'].incomeRate" :class="netWorthExtendBeanList[$index]['3'].incomeRate>=0?'positiveFc':'negativeFc'">
              {{ netWorthExtendBeanList[$index]['3'].incomeRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="近6月收益率" align="center" width="130">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['6']&&netWorthExtendBeanList[$index]['6'].incomeRate" :class="netWorthExtendBeanList[$index]['6'].incomeRate>=0?'positiveFc':'negativeFc'">
              {{ netWorthExtendBeanList[$index]['6'].incomeRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="今年以来收益率" align="center" width="150">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['0']&&netWorthExtendBeanList[$index]['0'].incomeRate" :class="netWorthExtendBeanList[$index]['0'].incomeRate>=0?'positiveFc':'negativeFc'">
              {{ netWorthExtendBeanList[$index]['0'].incomeRate }}%  
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="收益率" align="center" width="150">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['99']&&netWorthExtendBeanList[$index]['99']&&netWorthExtendBeanList[$index]['99'].incomeRate" :class="netWorthExtendBeanList[$index]['99'].incomeRate>=0?'positiveFc':'negativeFc'">
              {{ netWorthExtendBeanList[$index]['99'].incomeRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
         <el-table-column prop="" label="近1月最大回撤" align="center" width="140">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['1']&&netWorthExtendBeanList[$index]['1'].maxDownRate">
              {{ netWorthExtendBeanList[$index]['1'].maxDownRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="近3月最大回撤" align="center" width="140">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['3']&&netWorthExtendBeanList[$index]['3'].maxDownRate">
              {{ netWorthExtendBeanList[$index]['3'].maxDownRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="近6月最大回撤" align="center" width="140">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['6']&&netWorthExtendBeanList[$index]['6'].maxDownRate">
              {{ netWorthExtendBeanList[$index]['6'].maxDownRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="今年以来最大回撤" align="center" width="160">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['0']&&netWorthExtendBeanList[$index]['0'].maxDownRate">
              {{ netWorthExtendBeanList[$index]['0'].maxDownRate }}%  
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="最大回撤" align="center" width="160">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['99']&&netWorthExtendBeanList[$index]['99']&&netWorthExtendBeanList[$index]['99'].maxDownRate">
              {{ netWorthExtendBeanList[$index]['99'].maxDownRate }}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="夏普比率" align="center" width="180">
          <template slot-scope="{$index}">
            <span v-if="netWorthExtendBeanList[$index]['99']&&netWorthExtendBeanList[$index]['99']&&netWorthExtendBeanList[$index]['99'].sharpeRate">
              {{ netWorthExtendBeanList[$index]['99'].sharpeRate }}
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="" label="成立日期" align="center" width="120">
          <template slot-scope="{row}">
            <span>{{ row.strategyInfoVo.makeTime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="netwoth" label="单位净值" align="center" width="120"></el-table-column>
        <el-table-column prop="networthTime" label="最新净值日期" align="center" width="180"></el-table-column>
        <el-table-column prop="netWorthNumber" label="净值条数" align="center" width="100"></el-table-column>
        <el-table-column prop="completion" label="完整度" align="center" width="100">
          <template slot-scope="{row}">
            <span>{{ row.completion }}%</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="bottom-line">
        <div class="one">现金项</div>
        <div class="two">{{ Number(balance).toFixed(2) }}</div>
        <div class="three">{{ Number(have_weight).toFixed(2) }}</div>
      </div>
  </div>
</template>

<script>
import { savePortfolioStrategy, findPortfolioStrategy } from '@/api/combination'

export default {
  props: {
    chunk1_res: {
      type: Array,
      default: () => {
        return []
      }
    },
    weights: {
      type: Array,
      default: () => {
        return []
      }
    },
    portfolioId: {
      type: Number | String,
      required: true
    },
    base_contrast: {
      type: Number | String,
      required: true
    },
    model: {
      type: Object,
      default: () => {
        return {}
      }
    },
    userId: {
      type: Number | String,
      required: true
    },
    enterTime: {
      type: String,
      required: true
    },
    startMoney: {
      type: Number | String,
      default: ''
    },
  },
  data() {
    var vue = this
    return {
      dataForm: {
        makeTime: '',
        portfolioInitMoney: '',
        strategyPortfolioDetials: []
      },
      have_weight: 0,
      balance: 0,
      list: [],
      listLoading: false,
      pickerOptions1: {
        disabledDate(time) {
          return time.getTime() > new Date(vue.enterTime).getTime()
        }
      },
      pickerOptions2: {
        disabledDate(time) {
          return time.getTime() > new Date(vue.dataForm.makeTime).getTime()
        }
      },
      rules: {
        portfolioName: [
          { required: true, message: '请输入组合名称', trigger: 'blur' }
        ],
        portfolioInitMoney: [
          { required: true, message: '请输入初始资金', trigger: 'blur' }
        ],
        makeTime: [
          { required: true, message: '请选择成立日期', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.dataForm.portfolioCompareIndex = this.base_contrast
    this.dataForm.portfolioId = this.portfolioId
    this.dataForm.portfolioModelId = this.model.id+1
    this.dataForm.portfolioModelName = this.model.name
    this.dataForm.userId = this.userId
    this.dataForm.weights = this.weights
    this.dataForm.makeTime = this.enterTime
    this.dataForm.portfolioInitMoney = this.startMoney == '' ? undefined : this.startMoney
    if(this.chunk1_res.length>1) {
      this.getList(this.chunk1_res)
    }
  },
  methods: {
    makeTimeChange(val) {
      this.dataForm.strategyPortfolioDetials.forEach(item => {
        item.enterTime = val
      })
    },
    moneyChangeHandle(val) {
      this.dataForm.strategyPortfolioDetials.forEach(item => {
        const value = (val * item.weight / 100).toFixed(2)
        item.marketValue = value
        item.share = (value / item.netwoth * 10000).toFixed(2)
      })
      this.balance = (val * this.have_weight / 100).toFixed(2)
    },
    shareHandleChange(i) {},
    marketValueHandleChange(val, i) {
      
    },
    weightHandleChange(i) {
      let total = 0
      this.dataForm.strategyPortfolioDetials.forEach(item => {
        total += item.weight
      })
      if(total > 100) {
        this.$message({
          message: '超出最大权重',
          type: 'warning',
          duration: 2 * 1000
        })
        this.$nextTick(() => {
          this.have_weight = 0
          this.dataForm.strategyPortfolioDetials[i].weight = this.dataForm.strategyPortfolioDetials[i].weight - (total-100)
        })
      }else {
        this.have_weight = 100 - total
      }
      const weight = this.dataForm.strategyPortfolioDetials[i].weight
      const portfolioInitMoney = this.dataForm.portfolioInitMoney ? this.dataForm.portfolioInitMoney : 0
      const marketValue = (portfolioInitMoney * weight / 100).toFixed(2)
      this.dataForm.strategyPortfolioDetials[i].marketValue = marketValue
      this.dataForm.strategyPortfolioDetials[i].share = (marketValue / this.dataForm.strategyPortfolioDetials[i].netwoth * 10000).toFixed(2)
      this.balance = (portfolioInitMoney * this.have_weight / 100).toFixed(2)
    },
    savePortfolioStrategy(tableRiskData) {
      if(tableRiskData) {
        tableRiskData.forEach((item, i) => {
          this.dataForm.strategyPortfolioDetials[i].annualFluctuations = item.annualFluctuations
          this.dataForm.strategyPortfolioDetials[i].annualizedIncome = item.annualizedIncome
          this.dataForm.strategyPortfolioDetials[i].fluctuationsSegment = item.fluctuationsSegment
          this.dataForm.strategyPortfolioDetials[i].incomSegment = item.incomSegment
          this.dataForm.strategyPortfolioDetials[i].percentageDown = item.percentageDown
          this.dataForm.strategyPortfolioDetials[i].percentageUp = item.percentageUp
        })
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          savePortfolioStrategy({
            ...this.dataForm
          }).then(res => {
            if(res.body) {
              this.$message({ 
                message: '创建成功',
                type: 'success',
                duration: 2 * 1000
              })
              this.$store.dispatch("tagsView/delView", this.$route)
              this.$router.push('/strategyComb/optimize')
            }
          })
        }
      })
    },
    getList(chunk1_res) {
      this.listLoading = true
      findPortfolioStrategy(chunk1_res).then(res => {
        this.listLoading = false
        this.netWorthExtendBeanList = res.body.map(item => item.netWorthExtendBean)
        let total_weight = 0
        res.body.forEach((item, i) => {
          total_weight += this.weights[i]
          this.dataForm.strategyPortfolioDetials.push({
            annualFluctuations: null, //预测年化波动
            annualizedIncome: null, //预测年化收益
            enterTime: this.enterTime, //进入组合时间
            fluctuationsSegment: null, //1月 3月 6月  12月
            incomSegment: null, //1月 3月 6月  12月
            marketValue: null, //市值
            netwoth: item.netwoth, //单位净值
            percentageDown: null, //占比下限
            percentageUp: null, //占比上限
            portfolioId: this.portfolioId, //组合id
            share: null, //份额
            strategyId: item.strategyInfoVo.strategyId, //策略id
            strategyName: item.strategyInfoVo.strategyName, //策略名称
            weight: this.weights[i] //权重
          })
        })
        this.have_weight = 100 - total_weight
        this.list = res.body
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.combination-add-chunk5 {
  .head {
    border: 1px solid #ccc;
    .h-title {
      padding: 0 10px;
      line-height: 35px;
      display: flex;
      justify-content: space-between;
      background: #f1f0f0;
      border-bottom: 1px solid #ccc;
    }
    .h-body {
      padding: 15px;
    }
  }
  .bottom-line {
    height: 32px;
    display: flex;
    align-items: center;
    background: #eee;
    margin-top: 4px;
    user-select: none;
    padding-left: 10px;
    div {text-align: center;}
    .two { margin-left: 464px; width: 90px;}
    .three { margin-left: 30px; width: 70px; }
  }
} 
</style>

